package com.heima.app.gateway.filter;


import com.heima.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component   //自动生效
@Slf4j
public class AuthFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取请求头里的token
        String token = request.getHeaders().getFirst("token");
     //判断当前路径是否是登录接口
        //1.获取当前接口
        if (request.getPath().toString().contains("login")) {//判断路径是否含有login
            return chain.filter(exchange);

        }
        //判断token里面是否为空
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//响应状态码401
            return response.setComplete(); //完成响应
        }
        //用jwt校验token
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);  //校验token
        if (i==1 || i==2){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//token失效响应状态码401
            return response.setComplete(); //完成响应
        }

        return chain.filter(exchange);


    }
}
